package com.suvel.study.filter;


import com.suvel.study.service.UserService;
import jdk.nashorn.internal.ir.annotations.Reference;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

import static com.suvel.study.contants.Contants.COOKIE_NAME;

@Slf4j
@Component
public class TokenFilter implements GlobalFilter, Ordered {

    @Reference
    private UserService userService;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String path = request.getPath().toString();
        System.out.println("进入TokenFilter：path="+path);
        if(path.startsWith("/user") || path.startsWith("/code")){
            // ⽤用户微服务和验证码微服务的请求不不过滤
            return chain.filter(exchange);
        }
        MultiValueMap<String, HttpCookie> cookies = request.getCookies();
        List<HttpCookie> cookie = cookies.get(COOKIE_NAME);
        if(cookie == null || cookie.size() == 0){
            //说明不包含token，拒绝访问
            System.out.println("在cookie中未检测到token，拒绝访问！！！");
            response.setStatusCode(HttpStatus.UNAUTHORIZED); // 状态码
            String data = "Request be denied!";
            DataBuffer wrap = response.bufferFactory().wrap(data.getBytes());
            return response.writeWith(Mono.just(wrap));
        }
        String token = cookie.get(0).getValue();
        //开始判断token是否有效
        String emailByToken = userService.info(token);
        System.out.println("emailByToken="+emailByToken);
        if(StringUtils.isEmpty(emailByToken)){
            //无效的token,拒绝放行
            System.out.println("无效的token，拒绝访问！！！");
            response.setStatusCode(HttpStatus.UNAUTHORIZED); // 状态码
            String data = "Request be denied!";
            DataBuffer wrap = response.bufferFactory().wrap(data.getBytes());
            return response.writeWith(Mono.just(wrap));
        }else{
            //合法token，放行
            return chain.filter(exchange);
        }
    }

    /**
     * 返回值表示当前过滤器的顺序(优先级)，数值越小，优先级越高
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
